﻿using System.IO;
using UnityEditor;
using UnityEditor.Experimental.AssetImporters;
using UnityEngine;
using Util;

[ScriptedImporter(1, "lua")]
public class LuaImporter : ScriptedImporter
{
    private static Texture2D icon;
    public static Texture2D Icon { get { if (!icon) { icon = AssetDatabase.LoadAssetAtPath<Texture2D>("Assets/Arts/logo.png"); } return icon; } }

    public override void OnImportAsset(AssetImportContext ctx)
    {
        var text = File.ReadAllText(ctx.assetPath);
        var asset = new TextAsset(text);
        ctx.AddObjectToAsset("text ", asset, Icon);
        ctx.SetMainObject(asset);
    }
}

public class LuaFastProcessor : AssetPostprocessor
{
    [MenuItem("Assets/Create/Lua")]
    public static void CreationLua()
    {
        var paht = AssetDatabase.GetAssetPath(Selection.activeObject);
        FileIO.Save(paht + "/", "newLua" + debug.Sole + ".lua", "");
        AssetDatabase.Refresh();
    }

    public static void OnPostprocessAllAssets(string[] importedAsset, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        for (int i = 0; i < importedAsset.Length; i++)
        {
            var path = importedAsset[i];
            bool isLuaFile = path.EndsWith(LuaFileMgr.LUA_TYPE);
            if (isLuaFile)
            {
                bool isLuaPaht = path.StartsWith(LuaFileMgr.LUA_MAIN_PATH);
                if (isLuaPaht)
                {
                    LuaFileMgr.CreateAndUpdate(path);
                }
            }
        }
        for (int i = 0; i < deletedAssets.Length; i++)
        {
            var path = deletedAssets[i];
            bool isLuaFile = path.EndsWith(LuaFileMgr.LUA_TYPE);
            if (isLuaFile)
            {
                bool isLuaPaht = path.StartsWith(LuaFileMgr.LUA_MAIN_PATH);
                if (isLuaPaht)
                {
                    LuaFileMgr.Delete(path);
                }
            }
        }
        for (int i = 0; i < movedAssets.Length; i++)
        {
            var path = movedAssets[i];
            bool isLuaFile = path.EndsWith(LuaFileMgr.LUA_TYPE);
            if (isLuaFile)
            {
                bool isLuaPaht = path.StartsWith(LuaFileMgr.LUA_MAIN_PATH);
                if (isLuaPaht)
                {
                    LuaFileMgr.CreateAndUpdate(path);
                }
            }
            path = movedFromAssetPaths[i];
            isLuaFile = path.EndsWith(LuaFileMgr.LUA_TYPE);
            if (isLuaFile)
            {
                bool isLuaPaht = path.StartsWith(LuaFileMgr.LUA_MAIN_PATH);
                if (isLuaPaht)
                {
                    LuaFileMgr.Delete(path);
                }
            }
        }

        LuaFileMgr.ExamineCache();
    }
}